<?php

namespace app\uniapp\service;

use app\model\site\UserAddress;
use app\uniapp\service\traits\InstanceTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;

class UserAddressService extends UniBaseService
{

    use InstanceTrait;

    function initialize()
    {
        $this->model = new UserAddress();
    }


    public function query(): Query
    {
        return $this->makeQuery()->where('status',1)->where('user_id', $this->userId)->filter(function ($v){
            $v->location = [
                'p_id' => $v->province_id,
                'c_id' => $v->city_id,
                'd_id' => $v->district_id,
                'area_title' => $v->area_title,
                'address' => $v->address,
                'location' => [
                    'lng' => $v->lng,
                    'lat' => $v->lat,
                ]
            ];
        });
    }

    function formatData(array $data): array
    {
        $data['user_id'] = $this->userId;
        if ($data['location']??''){
            $loc = $data['location'];
            $data['province_id'] = $loc['p_id'];
            $data['city_id'] = $loc['c_id'];
            $data['district_id'] = $loc['d_id'];
            $data['area_title'] = $loc['area_title'];
            $data['address'] = $loc['address'];
            $data['lat'] = $loc['location']['lat'];
            $data['lng'] = $loc['location']['lng'];
        }
        return $data;
    }


    /**
     * 获取默认地址
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    function getDefault(){
        return self::instance()->setWhere([
            ['is_default', '=', 1],
            ['user_id', '=', $this->userId]
        ])->find();
    }
}
